package com.ht.api.call.func.impl.ad;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.util.HtUtil;
import com.ht.api.task.ad.CreatePlanUserTask;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 启动广告计划
 * @author asq
 * @createTime 2025年3月12日 13:31:46
 */
@Slf4j
public class StartPlanFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "启动广告计划";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();

		// 查询广告计划
		String planId = param.getStr("plan_id");
		if (StrUtil.isBlank(planId)) {
			throw new HtException("plan_id参数不能为空~");
		}
		Entity plan = Db.createSqlParser("ad_plan").where("main_id", planId).findOne(ds);
		if (plan == null) {
			throw new HtException("plan_id不存在：" + planId);
		}

		// 查询广告策略
        String campaignId = plan.getStr("campaign_id");

        long ampaignItemCount = Db.createSqlParser("ad_campaign_item").where("campaign_id", campaignId).count(ds);
        if (ampaignItemCount == 0) {
        	throw new HtException("未创建广告策略，不能启动计划！");
        }

		JSONObject taskParam = JSONUtil.createObj();
		taskParam.set("plan", plan);
		taskParam.set("tenant_id", me.getTenantId());
		taskParam.set("user_id", me.getLoginIdStr());

		HtTaskExecutor.submitTask(taskParam, new CreatePlanUserTask());

        plan.set("status", 7);//初始化中
        plan.set("start_time", DateUtil.now());
        Db.insert(ds, plan);

		HtUtil.createLog(ds, planId, "初始化中");

		return JSONUtil.createObj();
	}

}
